package postAPI

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"go-gin-init/app/models/model"
	"go-gin-init/app/models/req"
	"go-gin-init/app/service"
	"go-gin-init/common/ctx"
	"go-gin-init/common/result"
	"go-gin-init/common/tool"
	"go-gin-init/common/xerr"
)

// PostCreate
// @Summary 新增帖子
// @Description
// @Tags POST
// @Accept json
// @Produce json
// @Param Param body req.PostCreateReq true "请求参数"
// @Success 200 {object} result.JsonResult "{"code":200,"data":{},"msg":"SUCCESS"}"
// @Failure 400 {object} result.JsonResult "{"code":200,"data":{},"msg":""}"
// @Failure 500 {string} string "Internal Server Error"
// @Router /post/add [post]
func PostCreate(c *gin.Context) {

	var u req.PostCreateReq

	if err := c.ShouldBind(&u); err != nil {
		result.ParamErrorResult(c, err)
		return
	}

	if err := ctx.CheckPermissionCtx(u.AuthorId, c); err != nil {
		result.JsonRsp(c, nil, err)
		return
	}

	defaultPostModel := service.NewDefaultPostModel()

	p, err := defaultPostModel.FindByTitle(u.Title)
	if err != nil && !errors.Is(err, service.ErrNotFound) {
		result.JsonRsp(c, nil, xerr.NewErrCode(xerr.SERVER_COMMON_ERROR))
		return
	}

	if p != nil {
		result.JsonRsp(c, nil, xerr.NewErrMsg("帖子标题重复"))
		return
	}

	var post = model.Post{}
	copier.Copy(&post, u)

	postMap := tool.StructToMap(u)
	// 处理tags数组
	postMap["Tags"] = tool.Array2string(u.Tags)

	err = defaultPostModel.CreatPost(postMap)
	if err != nil {
		result.JsonRsp(c, nil, xerr.NewErrCode(xerr.SERVER_COMMON_ERROR))
		return
	}

	result.JsonRsp(c, nil, nil)

}
